package com.lagou.email.controller;

import com.lagou.email.bean.AuthCode;
import com.lagou.email.dao.AuthCodeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.time.LocalDateTime;

//@RestController
//@RequestMapping("")
public class EmailController {

    @Autowired
    private RedisTemplate<String,  String> redisTemplate;

    @Autowired
    AuthCodeRepository authCodeRepository;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("/{email}/{code}")
    @Transactional
    public boolean sendCode(@PathVariable("email") String email, @PathVariable("code") String code){
        LocalDateTime now = LocalDateTime.now();

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(now);
        authCode.setExpiretime(now.plusMinutes(5));
        sendSimpleMail(email, code);
        authCodeRepository.deleteByEmail(email);
        authCodeRepository.save(authCode);
        System.out.println("--------------验证码：" + code);
        return true;
    }

    void sendSimpleMail(String to, String code){
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject("注册验证码");
        //邮件内容
        message.setText(code);
        //发送邮件
        mailSender.send(message);
    }


}
